package com.alibaba.study.servlet3;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Alex
 *
 */
public class Handler {
	public static void handler(HttpServletRequest req,HttpServletResponse res,ExecutorService es,boolean async) throws IOException{
		if(async){
			if(es == null){
				throw new NullPointerException();
			}
			
			AsyncContext ac = req.startAsync();
	    	es.submit(()->{
	    		ac.addListener(new AsyncListener() {
					@Override
					public void onTimeout(AsyncEvent event) throws IOException {
					}
					
					@Override
					public void onStartAsync(AsyncEvent event) throws IOException {
						
					}
					
					@Override
					public void onError(AsyncEvent event) throws IOException {
						event.getSuppliedResponse().getWriter().println("error");
					}
					
					@Override
					public void onComplete(AsyncEvent event) throws IOException {
						event.getSuppliedResponse().getWriter().println("async");
					}
				});
	    		logic();
	    		ac.complete();
	    	});
			
			
		}else{
			logic();
			res.getWriter().println("sync");
		}
	}
	public static void logic(){
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
